package com.skin.admin.manager;

import com.skin.admin.common.FastDFSClient;
import com.skin.admin.entity.FastDFSFile;
import com.skin.admin.entity.Goods;
import com.skin.admin.entity.Uploadfile;
import com.skin.admin.serviceImpl.GoodsServiceImpl;
import com.skin.admin.serviceImpl.UploadfileServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by Administrator on 2018/8/9 0009.
 */
@Component
public class UploadfileManager {

    private static final Logger logger= LoggerFactory.getLogger(UploadfileManager.class);

    @Value("${image.path}")
    private String imagepath;

    private String datePath=new SimpleDateFormat("yyyyMMdd").format(new Date());

    @Autowired
    UploadfileServiceImpl uploadfileService;

    @Autowired
    GoodsServiceImpl goodsService;

    /**
     * 保存图片
     * @param uploadfile
     * @return
     */
    public Boolean saveimg(Uploadfile uploadfile){
        return uploadfileService.insert(uploadfile);
    }


    /**
     * 保存图片 商品缩略图
     * @param multipartFile
     * @param request
     * @return
     * @throws Exception
     */
    public Integer saveimgdb(MultipartFile multipartFile,HttpServletRequest request) throws Exception {

        String dateimagepath=imagepath+datePath;//日期分类文件夹
        String userid=request.getParameter("userid");
        String goodsid=request.getParameter("goodsid");
        if(StringUtils.isBlank(userid)){
            return 2;
        }
        String root_fileName = multipartFile.getOriginalFilename();
        logger.info("上传图片:name={},type={}", root_fileName, multipartFile.getContentType());
        String datePath=new SimpleDateFormat("yyyyMMdd").format(new Date());
        String name = saveimglocal(multipartFile,dateimagepath);
//        String name =saveFile(multipartFile);
        if(StringUtils.isNotBlank(name) && !"false".equals(name) && StringUtils.isNotBlank(goodsid)) {
            String savedbpath="/images/"+datePath+"/"+name;//springboot项目读取硬盘的
            Uploadfile uploadfile = new Uploadfile();
            uploadfile.setUserid(Integer.parseInt(userid));
            uploadfile.setName(root_fileName);
            uploadfile.setNewname(name);
            uploadfile.setTime(datePath);
            uploadfile.setPath(savedbpath);
            uploadfile.setGoodsid(goodsid);
            uploadfile.setReadpath(dateimagepath+name);
            uploadfile.setPosition(1);
            uploadfileService.insert(uploadfile);
            Goods goods=goodsService.selectById(goodsid);
            goods.setHeadimage(savedbpath);
            goodsService.updateById(goods);
        }else{
            return 0;
        }
        return 1;
    }
    /**
     * 保存图片到本地
     * @param multipartFile
     * @return
     * @throws Exception
     */
    private String saveimglocal(MultipartFile multipartFile,String path) throws Exception{
        if(!multipartFile.isEmpty()){
            //根据日期来创建对应的文件夹
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();

            String imagecontentType=multipartFile.getContentType().substring(multipartFile.getContentType().indexOf("/")+1);//文件后缀

            String fileName = UUID.randomUUID().toString().replace("-","")+"."+imagecontentType;
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
            byte[] bs = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bs)) != -1) {
                bos.write(bs, 0, len);
            }
            bos.flush();
            bos.close();
            return fileName;
        }
        return "false";
    }

    /**
     * 获取tomcat路径保存图片
     * @return
     */
    private String getpath(){
        String pic_path;
        //获取Tomcat服务器所在的路径
        String tomcat_path = System.getProperty( "user.dir" );
        //获取Tomcat服务器所在路径的最后一个文件目录
        String bin_path = tomcat_path.substring(tomcat_path.lastIndexOf("\\")+1,tomcat_path.length());
            //若最后一个文件目录为bin目录，则服务器为手动启动
        if(("bin").equals(bin_path)){//手动启动Tomcat时获取路径为：D:\Software\Tomcat-8.5\bin
            //获取保存上传图片的文件路径
            pic_path = tomcat_path.substring(0,System.getProperty( "user.dir" ).lastIndexOf("\\")) +"\\webapps"+"\\images\\";
        }else{//服务中自启动Tomcat时获取路径为：D:\Software\Tomcat-8.5
            pic_path = tomcat_path+"\\webapps"+"\\images\\";
        }

        return pic_path;
    }

    /**
     * FastDFS 上传图片
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath={};
        String fileName=multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream=multipartFile.getInputStream();
        if(inputStream!=null){
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
        try {
            fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
        } catch (Exception e) {
            logger.error("upload file Exception!",e);
        }
        if (fileAbsolutePath==null) {
            logger.error("upload file failed,please upload again!");
        }
        String path= FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
        return path;
    }

}
